//
//  CNEmoticonManager.swift
//  EmoticonKeyboard
//
//  Created by 陈锦聪 on 16/4/1.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

let CNEmoNumberOfPage = 20
let CNEmoColumnOfPage = 7
let CNEmoRowOfPage = 3
let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/recentEmoticons.plist")

class CNEmoticonManager: NSObject {
    
    static let sharedInstance: CNEmoticonManager = CNEmoticonManager()
    
    private override init() {
        super.init()
    }
    // 加载单个表情包
    private func loadPackage(id: String) -> CNPackageModel {
        let infoPath = bundlePath + "/" + id + "/" + "info.plist"
        let infoDict = NSDictionary(contentsOfFile: infoPath)!
        let group_name_cn = infoDict["group_name_cn"] as! String
        let array = infoDict["emoticons"] as! [[String: String]]
        var emoticons = [CNEmoticonModel]()
        for dict in array {
            emoticons.append(CNEmoticonModel(dict: dict,id: id))
        }
        return CNPackageModel(id: id, group_name_cn: group_name_cn, emoticons: emoticons)
    }
    // 加载多个表情包
    private func loadPackages() -> [CNPackageModel] {
        var packages = [CNPackageModel]()
        let recent = CNPackageModel(id: "", group_name_cn: "最近", emoticons: loadRecentEmoticons())
        packages.append(recent)
        packages.append(loadPackage("com.sina.default"))
        packages.append(loadPackage("com.apple.emoji"))
        packages.append(loadPackage("com.sina.lxh"))
        return packages
    }
    /// 添加最近表情
    func addFavorite(emoticon: CNEmoticonModel) {
        var recentEmoticons = packages[0].pageEmos[0]
        // 过滤: 'return true'为选中,保存在返回值中
        let sameEmoticons = recentEmoticons.filter { (emo) -> Bool in
            if emoticon.emoji != nil {
                return emoticon.code == emo.code
            } else {
                return emoticon.chs == emo.chs
            }
        }
        if let sameEmoticon = sameEmoticons.first {
            let index = recentEmoticons.indexOf(sameEmoticon)
            recentEmoticons.removeAtIndex(index!)
        }
        recentEmoticons.insert(emoticon, atIndex: 0)
        while recentEmoticons.count > CNEmoNumberOfPage {
            recentEmoticons.removeLast()
        }
        // 与OC不同: 需要赋值回去
        packages[0].pageEmos[0] = recentEmoticons
        saveRecentEmoticons(recentEmoticons)
    }
    // MARK: - 归档与解档
    private func saveRecentEmoticons(emoticons: [CNEmoticonModel]) {
        NSKeyedArchiver.archiveRootObject(emoticons, toFile: filePath)
    }
    private func loadRecentEmoticons() -> [CNEmoticonModel] {
        if let emoticons = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? [CNEmoticonModel] {
            return emoticons
        } else {
            return [CNEmoticonModel]()
        }
    }
    /// 所有表情包
    lazy var packages: [CNPackageModel] = self.loadPackages()
}
